package com.example.logisticsingle.utils;


import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.authorization.AuthProperties;
import com.example.logisticsingle.entity.SSOUser;
import org.springframework.stereotype.Component;

/**
 * SSO登录信息存储
 * @author Roskin
 *
 */
@Component
public class SSOLoginStoreHelper {
	/**
	 * 用户登录信息存储在缓存
	 * @param token	登录token
	 * @param user	用户
	 * @param expireTime	过期时间
	 */
	public static void put(String token, SSOUser user, long expireTime) {
		String key = getKeyByToken(token);
		if(StringUtils.isNotNull(key)) {
			RedisUtils.set(key, user, expireTime);
			RedisUtils.set(key+"_expire", expireTime,expireTime);
		}
		
	 }
	/**
	 * 根据Token获取用户信息
	 * @param token
	 * @return
	 */
	public static SSOUser get(String token) {
		String key = getKeyByToken(token);
		Object objectValue =  RedisUtils.get(key);
		if(null != objectValue) {
			SSOUser user = (SSOUser) objectValue;
			return user;
		}
		return null;
	}
	/**
	 * 从Redis中移除Session
	 * @param storeKey
	 */
	public static void remove(String token) {
		String key = getKeyByToken(token);
        RedisUtils.del(key,key+"_expire");
    }
	/**
	 * 更新Token信息
	 * @param token
	 */
	public static void updateToken(String token) {
		String key = getKeyByToken(token);
		if(RedisUtils.hasKey(key)) {
			Object valueObj = RedisUtils.get(key+"_expire");
			Integer obj = (Integer) valueObj;
			long expireTime = obj.longValue();
			RedisUtils.expire(key, expireTime);
			RedisUtils.expire(key+"_expire", expireTime);
		}
	}
	/**
	 * Token是否存在
	 * @param token
	 * @return
	 */
	public static boolean hasToken(String token) {
		String key = getKeyByToken(token);
		return StringUtils.isNotNull(key)?RedisUtils.hasKey(key):false;
	}
	/**
	 * 解析token值
	 * @param token
	 * @return
	 */
	private static String getKeyByToken(String token) {
		String prefix = AuthProperties.token.prefix;
		String key = null;
		if(StringUtils.isNotNull(token) && token.startsWith(prefix)) {
			key = token.substring(prefix.length());
		}
		return key;
	}
}
